package com.fesine.ssh.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.fesine.ssh.model.User;
import com.fesine.ssh.service.SequenceService;
import com.fesine.ssh.service.UserService;
import com.fesine.ssh.util.DateUtil;
import com.fesine.ssh.util.GenerateUUID;
import com.fesine.ssh.util.ResponseUtil;
import com.fesine.ssh.util.ShopException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.List;

/**
 * Created by Fesine on 2016/2/21.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = Logger.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private SequenceService sequenceService;

    public static SerializeConfig mapping = new SerializeConfig();
    //private static String dateFormat;
    //static {
    //    dateFormat = "yyyy-MM-dd HH:mm:ss";
    //    mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat));
    //}

    /**
     * 根据用户Id查询用户信息
     *
     * @param modelMap
     * @param userId
     * @return
     */
    @RequestMapping("/{userId}/showInfo")
    public String showUserInfo(ModelMap modelMap, @PathVariable String userId) {
        logger.info("查询用户：" + userId);
        User userInfo = userService.findByUserId(userId);
        modelMap.addAttribute("userInfo", userInfo);
        return "/user/showInfo";
    }

    /**
     * 分页查询用户信息
     *
     * @param req
     * @param resp
     * @throws Exception
     */
    @RequestMapping("/listUser")
    public void listUser(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        String offset = req.getParameter("start");
        String pageSize = req.getParameter("limit");
        logger.info("分页查询用户信息，offset:[" + offset + "],pageSize:[" + pageSize + "]");
        int total = userService.findAll().size();
        JSONObject jsonObject = new JSONObject();
        List<User> useList = userService.
                findAll(Integer.parseInt(offset), Integer.parseInt(pageSize));
        jsonObject.put("total", total);
        logger.info("------->查询总记录数[" + total + "]");
        String str = JSON.toJSONString(useList, mapping);
        JSONArray jsonArray = JSON.parseArray(str);
        jsonObject.put("rows", jsonArray);
        logger.info("--------->" + jsonObject);
        ResponseUtil.write(resp, jsonObject);
    }

    /**
     * 添加用户
     *
     * @param req
     * @param resp
     * @throws Exception
     */
    @RequestMapping("/addUser")
    public void addUser(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        Writer writer = resp.getWriter();
        StringBuffer sb = new StringBuffer();
        String username = req.getParameter("username");
        //如果用户名存在，返回true
        if (userService.checkUsername(username)) {
            sb.append("{success:false,msg:'用户名已经存在!'}");
        } else {
            String password = req.getParameter("password");
            String sex = req.getParameter("sex");
            String phone = req.getParameter("phone");
            String qq = req.getParameter("qq");
            String email = req.getParameter("email");
            String address = req.getParameter("address");
            User user = new User();
            user.setId(GenerateUUID.getUUId());
            user.setUserId(sequenceService.genUserId());
            user.setUsername(username);
            user.setPassword(password);
            user.setSex(sex);
            user.setPhone(phone);
            user.setQq(qq);
            user.setEmail(email);
            user.setAddress(address);
            user.setRegTime(new Date());
            user.setUpdateTime(new Date());
            String id = userService.register(user);
            if (null != id) {
                sb.append("{success:true,msg:'用户添加成功!'}");
                logger.info("------->添加成功！");
            } else {
                sb.append("{success:false,msg:'用户添加失败!'}");
                logger.info("------->添加失败！");
            }
        }
        writer.write(sb.toString());
    }

    @RequestMapping("/updateUser")
    public void updateUser(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        Writer writer = resp.getWriter();
        StringBuffer sb = new StringBuffer();
        String userId = req.getParameter("userId");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        String phone = req.getParameter("phone");
        String qq = req.getParameter("qq");
        String email = req.getParameter("email");
        String address = req.getParameter("address");
        String regTime = req.getParameter("regTime");
        User user = userService.findByUserId(userId);//根据userId查询用户信息
        user.setPassword(password);
        user.setSex(sex);
        user.setPhone(phone);
        user.setQq(qq);
        user.setEmail(email);
        user.setAddress(address);
        user.setRegTime(DateUtil.formatString(regTime, "yyyy-MM-dd HH:mm:ss"));
        user.setUpdateTime(new Date());
        userService.modify(user);
        sb.append("{success:true,msg:'用户修改成功!'}");
        logger.info("------->更新成功！");
        //}
        writer.write(sb.toString());
    }

    @RequestMapping("/deleteUser")
    public void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userIds = req.getParameter("userIds").replace("\"", "");
        String[] IdsArr = userIds.split(",");
        //for (String s : IdsArr) {
        //    logger.info("--------->"+ s);
        //}
        StringBuffer sb = new StringBuffer();
        try {
            userService.delete(IdsArr);
            sb.append("{success:true,msg:'用户删除成功!'}");
            logger.info("------->删除用户成功！");
        } catch (ShopException e) {
            logger.info("------->删除用户失败！");
            sb.append("{success:false,msg:'用户删除失败!'}");
            e.printStackTrace();
        }

        Writer writer = resp.getWriter();
        writer.write(sb.toString());

    }

    @RequestMapping("/checkUsername")
    public void checkUsername(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        Writer writer = resp.getWriter();
        StringBuffer sb = new StringBuffer();
        String username = req.getParameter("username");
        if (userService.checkUsername(username)) {
            sb.append("{success:false,msg:'用户名已经存在!'}");
        } else {
            sb.append("{success:true,msg:'用户名可以使用!'}");
        }
        writer.write(sb.toString());
    }

    @RequestMapping("/login")
    public void login(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        Writer writer = resp.getWriter();
        StringBuffer sb = new StringBuffer();
        String username = req.getParameter("username");
        String captchaToken = ((String) req.getSession().getAttribute("captchaToken")).toLowerCase();
        String checkCode = req.getParameter("checkCode").toLowerCase();
        logger.info("----->captchaToken:"+ captchaToken+",checkCode:"+checkCode);
        //不区分大小写
        if (!captchaToken.equals(checkCode.toLowerCase())) {
            sb.append("{success:false,msg:'验证码错误!'}");
        } else {
            if (userService.checkUsername(username)) {
                //用户名正确，再验证密码
                String password = req.getParameter("password");
                if (userService.login(username, password)) {
                    sb.append("{success:true,msg:'登录成功!'}");
                    //创建用户session
                    HttpSession session = req.getSession();
                    session.setAttribute("username", username);
                } else {
                    sb.append("{success:false,msg:'登录失败，密码错误!'}");
                }
            } else {
                sb.append("{success:false,msg:'用户名输入有误!'}");
            }
        }
        /**解决乱码问题*/
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;  charset=UTF-8");
        writer.write(sb.toString());
    }

    @RequestMapping("/logout")
    public void logout(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        req.getSession().invalidate();
        Writer writer = resp.getWriter();
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;  charset=UTF-8");
        StringBuffer sb = new StringBuffer();
        sb.append("{success:true,msg:'注销成功!'}");
        writer.write(sb.toString());
        //resp.sendRedirect("/ssh-master/oms/login.jsp");
    }
}
